package service

import (
	. "Go-Easy/pkg/config"
	. "Go-Easy/pkg/etcd"
	. "Go-Easy/pkg/microservice/credentials"
	"google.golang.org/grpc"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
)

type easyService struct {
	ServiceName    string
	server_options []grpc.ServerOption
	cfg Config_Service
}

func NewEasyService(ServiceName string,ServerOption ...grpc.ServerOption) *easyService {
	return &easyService{
		ServiceName:ServiceName,
		server_options:ServerOption,
		cfg:ServiceMap[ServiceName],
	}
}

func (e *easyService) CreateNewServer() (*grpc.Server, error) {
	//获取配置项
	//cfg := ServiceMap[es.ServiceName]
	//如果配置需要在ETCD中注册服务
	if e.cfg.ServiceRegistry {
		//关闭信号处理(关闭时撤销注册)
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)
		go func() {
			s := <-ch
			EtcdUnRegistService(e.cfg.ServiceName,e.cfg.Address)
			if i, ok := s.(syscall.Signal); ok {
				os.Exit(int(i))
			} else {
				os.Exit(0)
			}
		}()

		//注册etcd端点
		err := EtcdRegistService(e.cfg.ServiceName,e.cfg.ServiceTTL,e.cfg.Address)
		if err != nil {
			return nil, err
		}
	}

	var options []grpc.ServerOption

	//根据配置文件中TLS文件是否配置确定是否使用TLS协议
	if e.cfg.UseTLS {
		if cred, err := GenerateTLSCredentials(); err == nil {
			options = append(options, grpc.Creds(cred))
		} else {
			return nil, err
		}

	}
	//添加用户传入的ServerOption
	options = append(options, e.server_options...)

	grpcServer := grpc.NewServer(options...)

	return grpcServer, nil
}

func (e *easyService) RunService(s *grpc.Server) {
	//获取配置项
	cfg := ServiceMap[e.ServiceName]
	//开启服务端口
	lis, err := net.Listen("tcp", cfg.Address)
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("------运行服务[%s] 于 %s------", e.ServiceName, cfg.Address)
	if err = s.Serve(lis); err != nil {
		log.Fatalln(err)
	}
}
